<template>
  <el-card class="box-card">
    <!-- 头部标题 -->
    <div slot="header" class="clearfix">
      <span>试题录入</span>
    </div>
    <!-- 头部标题 -->
    <!--表单内容  -->
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <!-- 学科 -->
      <el-form-item label="学科:" prop="subjectID">
        <el-select
          v-model="ruleForm.subjectID"
          placeholder="请选择"
          @change="subjectChange(ruleForm.subjectID)"
        >
          <el-option
            v-for="(item, index) in subjects"
            :key="index"
            :label="item.label"
            :value="item.value"
          >{{ item.label }}</el-option>
        </el-select>
      </el-form-item>
      <!-- /学科 -->

      <!-- 目录 -->
      <el-form-item label="目录" prop="directoryName">
        <el-select v-model="ruleForm.directoryName" placeholder="请选择">
          <el-option label="无数据" value="无数据" class="nodata" v-if="directorys.length == 0"></el-option>
          <el-option
            :label="item.label"
            :value="item.label"
            v-else
            v-for="(item, index) in directorys"
            :key="index"
          >{{ item.label }}</el-option>
        </el-select>
      </el-form-item>
      <!-- /目录 -->

      <!-- 企业 -->
      <el-form-item label="企业:" prop="enterprise">
        <el-select v-model="ruleForm.enterprise" placeholder="请选择">
          <el-option
            :label="item.company"
            :value="item.company"
            v-for="item in companies"
            :key="item.id"
          >{{ item.company }}</el-option>
        </el-select>
      </el-form-item>
      <!-- /企业 -->

      <!-- 城市 -->
      <el-form-item label="城市:" class="city" prop="province">
        <el-select
          v-model="ruleForm.province"
          placeholder="请选择"
          @change="provinceChange(ruleForm.province)"
        >
          <el-option :label="item" :value="item" v-for="(item, index) in provinces" :key="index"></el-option>
        </el-select>
        <el-select v-model="ruleForm.city" placeholder="请选择" class="region">
          <el-option label="无数据" value="nodata" v-if="citys.length == 0" class="nodata"></el-option>
          <el-option :label="item" :value="item" v-else v-for="(item, index) in citys" :key="index"></el-option>
        </el-select>
      </el-form-item>
      <!-- /城市 -->

      <!-- 方向 -->
      <el-form-item label="方向:" prop="direction">
        <el-select v-model="ruleForm.direction" placeholder="请选择">
          <el-option :label="item" :value="item" v-for="(item, index) in direction" :key="index"></el-option>
        </el-select>
      </el-form-item>
      <!-- /方向 -->

      <!-- 题型 -->
      <el-form-item label="题型:" prop="questionType" required>
        <!-- <el-radio-group v-model="ruleForm.questionType" @change="typeChange"> -->
        <el-radio
          :label="item.value.toString()"
          v-for="item in questionType"
          :key="item.value"
          v-model="ruleForm.questionType"
          @change="typeChange"
        >{{ item.label }}</el-radio>
      </el-form-item>
      <!-- 题型 -->

      <!-- 难度 -->
      <el-form-item label="难度" prop="difficulty" required>
        <el-radio
          v-for="item in difficulty"
          :key="item.value"
          :label="item.value.toString()"
          v-model="ruleForm.difficulty"
        >{{ item.label }}</el-radio>
      </el-form-item>
      <!-- 难度 -->

      <!-- 题干 -->
      <el-form-item label="题干:" prop="question" class="edit_container">
        <quill-editor
          class="edit-container"
          v-model="ruleForm.question"
          ref="myQuillEditor"
          :options="editorOption"
          @blur="onEditorBlur($event)"
        ></quill-editor>
      </el-form-item>
      <!-- /题干 -->

      <!-- 选项 -->
      <el-form-item
        class="options"
        prop="options"
        label="选项:"
        v-if="isShow == true"
        ref="optionContainer"
      >
        <el-radio-group
          class="optionItem"
          v-if="isRadio == true"
          v-model="option"
          @change="radioChange"
        >
          <radio-option
            v-for="(item, index) in ruleForm.options"
            :key="index"
            :radioItem="item"
            :radioIndex="index"
            @changeIsRight="radioClick"
          ></radio-option>
        </el-radio-group>

        <el-checkbox-group v-model="checkList" class="optionItem" v-else @change="checklistChange">
          <checkbox-option
            v-for="(item, index) in ruleForm.options"
            :key="index"
            :checkboxItem="item"
            :checkboxIndex="index"
            :checkOptions="checkList"
          ></checkbox-option>
        </el-checkbox-group>
        <el-row>
          <el-button type="danger" size="mini" disabled v-if="isRadio == true">+增加选项与答案</el-button>
          <el-button type="danger" size="mini" v-else @click="addNum">+增加选项与答案</el-button>
        </el-row>
      </el-form-item>
      <!-- /选项 -->
      <!-- 解析视频 -->
      <el-form-item label="解析视频:" prop="videoURL">
        <el-input v-model="ruleForm.videoURL"></el-input>
      </el-form-item>
      <!-- /解析视频 -->

      <!-- 答案解析 -->
      <el-form-item label="答案解析:" prop="answer" class="edit_container">
        <quill-editor
          v-model="ruleForm.answer"
          ref="myQuillEditor1"
          :options="editorOption"
          @blur="onanswerEditorBlur($event)"
        ></quill-editor>
      </el-form-item>
      <!-- /答案解析 -->
      <!-- /题干 -->

      <!-- 题目备注 -->
      <el-form-item label="题目备注:">
        <el-input type="textarea" v-model="ruleForm.remarks" class="remarks"></el-input>
      </el-form-item>
      <!-- 题目备注 -->

      <!-- 试题标签 -->
      <el-form-item label="试题标签:" prop="tags">
        <el-select placeholder="请输入试题标签" multiple collapse-tags v-model="ruleForm.tags">
          <el-option label="无数据" value="无数据" v-if="subjects.length == 0" class="nodata"></el-option>
          <el-option
            :label="item.label"
            :value="item.label"
            v-else
            v-for="item in tags"
            :key="item.value"
          >{{ item.label }}</el-option>
        </el-select>
      </el-form-item>
      <!-- /试题标签 -->

      <!-- 提交按钮 -->
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">确认提交</el-button>
      </el-form-item>
      <!-- 提交按钮 -->
    </el-form>
    <!-- /表单内容 -->
  </el-card>
</template>

<script>
import { quillEditor, quill } from 'vue-quill-editor' // 调用编辑器
// 单选选项
import RadioOption from '../components/radioOption.vue'
// 复选选项
import CheckboxOption from '../components/checkboxOption.vue'
import '../../../node_modules/quill/dist/quill.core.css'
import '../../../node_modules/quill/dist/quill.snow.css'
import '../../../node_modules/quill/dist/quill.bubble.css'
// 引入获取学科列表接口
import { simple } from '@/api/hmmm/subjects.js'
// 引入获取简单目录列表接口
import { simple as simple1 } from '@/api/hmmm/directorys.js'

// 获取标签列表
import { simple as simple2 } from '@/api/hmmm/tags.js'
// 获取企业列表
import { list } from '@/api/hmmm/companys.js'
// 获取城市数据
import { provinces, citys } from '@/api/hmmm/citys.js'
// 获取方向数据
import { direction, difficulty, questionType } from '@/api/hmmm/constants.js'
// 获取基础题库详情,//添加基础题库
import { detail, add } from '@/api/hmmm/questions.js'
import { update } from '../../api/hmmm/companys'

const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'],
  [{ list: 'ordered' }, { list: 'bullet' }],
  ['blockquote'],
  ['code-block', 'image'],
  ['link']
]

export default {
  components: {
    RadioOption,
    CheckboxOption
  },
  data () {
    return {
      components: {
        quillEditor
      },
      id: '',
      subjects: [], // 学科列表数据
      directorys: [], // 目录列表
      companies: [], // 企业列表
      provinces: [], // 省份列表
      citys: [], // 城市列表
      direction: direction, // 方向
      difficulty: difficulty,
      questionType: questionType,
      tags: [], // 试题标签
      isRadio: true, // 单选
      isShow: true, // 选项显示
      optionsLabel: ['A', 'B', 'C', 'D'],
      option: '',
      checkList: [],
      // 富文本工具栏
      editorOption: {
        placeholder: '',
        modules: {
          toolbar: toolbarOptions
        }
      },

      ruleForm: {
        subjectID: '', // 科目
        directoryName: '', // 目录
        enterprise: '', // 企业
        province: '', // 省份
        city: '', // 城市
        questionType: '1', // 题型
        difficulty: '1', // 难度
        question: '', // 题干
        videoURL: '', // 视频解析
        answer: '', // 答案解析
        tags: [], // 试题标签
        remarks: '', // 题目备注
        direction: '', // 经营方向
        options: [
          { code: 'A', title: '', img: '', isRight: 0 },
          { code: 'B', title: '', img: '', isRight: 0 },
          { code: 'C', title: '', img: '', isRight: 0 },
          { code: 'D', title: '', img: '', isRight: 0 }
        ]
      },
      // 表单验证规则
      rules: {
        subjectID: [{ required: true, message: '请选择学科' }],
        directoryName: [{ required: true, message: '请选择目录' }],
        enterprise: [{ required: true, message: '请选择企业' }],

        province: [{ required: true, message: '请选择地区' }],
        city: [{ required: true, message: '请选择地区' }],

        direction: [{ required: true, message: '请选择方向' }],
        question: [{ required: true, message: '请输入题干', trigger: 'blur' }],
        answer: [{ required: true, message: '请输入答案解析', trigger: 'blur' }]
      }
    }
  },
  beforeRouteUpdate (to, from, next) {
    console.log(to)
    if (to.fullPath != from.fullPath) {
      next()
    }
    this.getCompanies()
  },
  watch: {
    $route: {
      handler (value) {
        // console.log(value)
        if (value.query.id) {
          this.id = this.$route.query.id
          this.getQuestionDetail(this.id)
        }
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    // 单选选项变化
    radioChange (val) {
      // console.log(val)
      this.ruleForm.options.forEach(item => (item.isRight = 0))
      this.ruleForm.options[val].isRight = 1
      // console.log(this.ruleForm.options)
    },
    // 复选框变化
    checklistChange (list) {
      // console.log(list)
      this.ruleForm.options.forEach(item => (item.isRight = 0))
      list.forEach(i => (this.ruleForm.options[i].isRight = 1))
      // console.log(this.ruleForm.options)
    },

    // 获取题库详情
    async getQuestionDetail (id) {
      // console.log(id)
      try {
        let res = await detail({ id: this.id })
        console.log(res.data)
        let data = res.data
        console.log(data)
        // 获取企业名字
        let enterprise = this.getCompanyName(data.enterpriseID)
        let {
          subjectID,
          directoryName,
          province,
          city,
          questionType,
          difficulty,
          question,
          videoURL,
          answer,
          tags,
          remarks,
          direction,
          options
        } = data
        this.ruleForm = {
          enterprise,
          subjectID,
          directoryName,
          province,
          city,
          questionType,
          difficulty,
          question,
          videoURL,
          answer,
          tags,
          remarks,
          direction,
          options
        }
        console.log(this.ruleForm)
        // 根据题型切换单选多选变量
        let res1 = this.getType(data.questionType)
        this.typeChange(data.questionType)

        // tags标签还原成数组
        this.ruleForm.remarks = data.remarks
        let tagsResult = data.tags.split(',')
        this.ruleForm.tags = tagsResult

        // 获取options数据
        let optionsResult = data.options
        if (res1 == '单选') {
          // 获取isRight是1的索引, 重新赋值
          let index = optionsResult.findIndex(item => item.isRight === 1)
          this.option = index
        } else if (res1 == '多选') {
          let arr = optionsResult.map(item => item.isRight)
          let indexs = this.findall(arr, 1)
          this.checkList = indexs
          this.ruleForm.options = optionsResult
        }
      } catch (err) {
        console.log(err)
      }
    },
    // 根据id转换成企业名字
    getCompanyName (id) {
      console.log(id)
      this.getCompanies()
      console.log(this.companies)
      if (this.companies.length > 0) {
        let companyResult = this.companies.filter(item => {
          return item.id == id
        })
        console.log(companyResult)
        return companyResult[0].company
      } else {
        return "用友"
      }
    },

    // 根据企业名字转换企业ID
    getCompanyID (name) {
      console.log(1)
      let companyID = this.companies.filter(item => {
        return item.company == name
      })
      //  console.log(companyResult)
      return companyID[0].id
    },
    // 根据目录名字返回目录ID
    getCatalogID (name) {
      let cataID = this.directorys.filter(item => {
        return item.label == name
      })
      if (cataID.length > 0) {
        //  console.log(companyResult)
        return cataID[0].value
      } else {
        return 1
      }

    },
    // 获取学科数据
    async getSubjects () {
      const { data } = await simple()
      // console.log(data)
      this.subjects = data
    },
    // 获取企业列表
    async getCompanies () {
      const { data } = await list()
      // console.log(data.items)
      this.companies = data.items
    },
    // 获取省份数据
    async getProvinces () {
      const res = await provinces()
      // console.log(res)
      this.provinces = res
    },
    // 选中学科
    async subjectChange (data) {
      // 获取目录数据
      const res = await simple1({ subjectID: data })
      this.directorys = res.data
      // console.log(this.directorys)
      // 获取标签数据
      const tagsRes = await simple2({ subjectID: data })
      // console.log(tagsRes.data)
      this.tags = tagsRes.data
    },
    // 省份与城市联动
    async provinceChange (Pname) {
      const res = await citys(Pname)
      this.citys = res
    },

    // 切换题型
    typeChange (value) {
      // console.log(value)
      if (value == '3') {
        this.isShow = false
      } else {
        this.isShow = true
        if (value == '1') {
          this.isRadio = true
        } else {
          this.isRadio = false
        }
      }
    },
    // 单选功能
    radioClick (i) {
      this.ruleForm.options.forEach(item => (item.isRight = 0))
      this.ruleForm.options[i].isRight = 1
    },

    // 增加选项
    addOptionItem () {
      const item = this.$refs.optionItem
      const group = this.$refs.optionGroup
      // console.log(item)
    },
    // 提交表单
    submitForm (formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          try {
            console.log(this.ruleForm.subjectID)
            const catalogID = this.getCatalogID(this.ruleForm.directoryName)
            const enterpriseID = this.getCompanyID(this.ruleForm.enterprise)
            const {
              subjectID,
              province,
              city,
              questionType,
              difficulty,
              question,
              videoURL,
              answer,
              remarks,
              direction,
              options
            } = this.ruleForm
            const commitData = {
              catalogID,
              enterpriseID,
              subjectID,
              province,
              city,
              questionType,
              difficulty,
              question,
              videoURL,
              answer,
              remarks,
              direction,
              options,
              tags: this.ruleForm.tags.join(',')
            }
            // this.ruleForm.tags = this.ruleForm.tags.join(',')
            const res = await add(commitData)
            this.$message({
              message: '添加成功',
              type: 'success'
            })
            this.$router.push('/questions/list')
            // console.log(res)
          } catch (err) {
            console.log(err)
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 增加选项
    addNum () {
      const arr = [
        'A',
        'B',
        'C',
        'D',
        'E',
        'F',
        'G',
        'H',
        'I',
        'J',
        'K',
        'L',
        'M',
        'N',
        'O',
        'P',
        'Q',
        'R',
        'S',
        'T',
        'U',
        'V',
        'X',
        'Y',
        'Z'
      ]
      let num = this.ruleForm.options.length
      num++
      this.optionsLabel = arr.splice(0, num)
      this.ruleForm.options.push({
        code: this.optionsLabel[this.optionsLabel.length - 1],
        title: '',
        img: '',
        isRight: 0
      })
    },

    // //根据数字转换题型
    getType (type) {
      const res = questionType.filter(item => {
        return item.value == type
      })
      return res[0].label
    },
    // 根据数字转换难度
    getDifficulty (diff) {
      const res = difficulty.filter(item => {
        return item.value == diff
      })
      return res[0].label
    },

    // 查找符合条件的数组索引
    findall (a, x) {
      var results = []
      var len = a.length
      var pos = 0
      while (pos < len) {
        pos = a.indexOf(x, pos)
        if (pos === -1) {
          // 未找到就退出循环完成搜索
          break
        }
        results.push(pos) // 找到就存储索引
        pos += 1 // 并从下个位置开始搜索
      }
      return results
    },

    // 富文本方法
    onEditorBlur () {
      // 失去焦点事件
      this.$refs.ruleForm.validateField('question')
    },

    onanswerEditorBlur () {
      // 失去焦点事件
      this.$refs.ruleForm.validateField('answer')
    }
  },
  created () {
    this.getSubjects()
    this.getCompanies()
    this.getProvinces()
  },

}
</script>

<style scoped >
.box-card {
  margin: 20px;
}
.el-select,
.el-input--medium {
  width: 400px;
}
.el-form-item {
  margin-bottom: 22px;
}
.city > .el-form-item__content {
  display: flex;
  width: 400px;
}
.city > .el-form-item__content .el-select--medium {
  width: 200px;
}

.region {
  margin-left: 3px;
}
.nodata {
  color: #999;
}
/* .optionItem {
  display: flex;
  align-items: center;
  padding-bottom: 20px;
} */
::v-deep.optionItem > #uploadInput {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 60px;
}
.optionItem > .el-input--medium {
  width: 240px;
}
.optionItem .item {
  margin-right: 10px;
}

::v-deep.el-icon-circle-close {
  position: absolute;
  top: 0;
  right: 0;
  transform: translate(50%, -50%);
  background: #fff;
  font-size: 18px;
  color: #999;
}
::v-deep .ql-container {
  height: 200px;
}
::v-deep.ql-toolbar {
  padding: 0;
}
::v-deep.remarks .el-textarea__inner {
  height: 96px;
}
</style>
